package cn.kent.high.juc.lock.reentrantLock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁中：读读不互斥，读写互斥，写写互斥
 */
public class ReentrantReadWriteLockTest2 {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();
    ReentrantReadWriteLock.ReadLock readLock = lock.readLock();

    public void read() {
        try {
            readLock.lock();
            System.out.println(Thread.currentThread().getName() + "进入readLock");
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + "退出readLock");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readLock.unlock();
        }
    }

    public void write() {
        try {
            writeLock.lock();
            System.out.println(Thread.currentThread().getName() + "进入writeLock");
            Thread.sleep(3000);
            System.out.println(Thread.currentThread().getName() + "退出writeLock");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final ReentrantReadWriteLockTest2 rw = new ReentrantReadWriteLockTest2();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                rw.read();
            }
        }, "t1");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                rw.read();
            }
        }, "t2");
        Thread t3 = new Thread(new Runnable() {
            public void run() {
                rw.write();
            }
        }, "t3");
        Thread t4 = new Thread(new Runnable() {
            public void run() {
                rw.write();
            }
        }, "t4");

        // 模拟读写 互斥
        // t1.start();
        // t3.start();

        // 模拟读读 不互斥
        // t1.start();
        // t2.start();

        // 模拟写写 互斥
        t3.start();
        t4.start();


        // t3.join();
        // t4.join();
    }
}
